package com.hdl.api;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 类名 CreateSession
 * 描述 建立会话
 *
 * @author hedonglin
 * @version 1.0
 * @date 2020/6/14 12:27
 */
public class CreateSession implements Watcher{

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    /**
     * 建立会话
     * @param args
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        /**
         * 客户端可以通过创建一个zk实例来连接zk服务器
         * new Zookeeper(connectString, sessionTimeOut, Watcher)
         * connectString连接地址， IP：端口
         * sessionTimeOut： 会话超时时间，单位毫秒
         * Watcher：监听器（当特定事件触发监听时，zk会通过watcher通知客户端）
         */
        ZooKeeper zooKeeper = new ZooKeeper("192.168.227.131:2181", 3000, new CreateSession());
        System.out.println(zooKeeper.getState());

        // 技术工具类：CountDownLatch: 不让Main方法结束，让线程处于等待阻塞
        countDownLatch.await();
        System.out.println("客户端与服务端会话真正建立了，当前状态为：" + zooKeeper.getState());
    }

    /**
     * 回调方法，处理来自服务器端的Watcher通知
     * @param event
     */
    public void process(WatchedEvent event) {
        // SyncConnected
        if (event.getState() == Event.KeeperState.SyncConnected){
            // 解除主程序在CountDownLatch上的等待阻塞
            System.out.println("process方法被执行了....");
            countDownLatch.countDown();
        }

    }
}
